<?php

namespace app\store\controller\zzindb;

use alibabasdk\AlibabaClient;
use alibabasdk\AlibabaException;
use think\Config;
use think\Db;
use think\Request;
use think\View;

class Alibasecontroller extends \think\Controller
{
    const wxapp_id = 10016;
    const shop_id = 10017;
    const net_from = 2;     //1：汪总渠道货源，2：阿里巴巴渠道货源

    public function getOldData($api, $params){
        $back = false;
        //$client = new AlibabaClient(5788670, 'Vy2mVRJVN4TQ', 'ef3ffc60-6ccf-4cb1-bed6-9f772da99d84');
        $client = new AlibabaClient(Config('ali_appid'), Config('ali_secret'), Config('ali_token'));
        try {
            $res = $client->post($api,$params); // post
            $back = $res;
            //dump($res);
            // $client->get($api,$params);  // get
        }catch (AlibabaException $e){
            echo $e->getMessage();
        }
        return $back;
    }
    /** 正式将选中的产品入库 */
    public function trueGoodInDb($bigGoodsArr){
        foreach($bigGoodsArr as $key => $value){
            // 0. 商品基本信息先入库，暂时无详情描述
            $goodIDArr = $this->goodInDbFunOne($value);
            $goodID = $goodIDArr['goodID'];
            $isNew = $goodIDArr['isNew'];
            if($isNew==true){
                // echo '<hr>+++处理第'. ($key+1) .'个商品+++<hr>';
                $perGeGoodsArr = $value['specificationList'];
                $goodBannerImgsArr = array();
                $finalGuigeValIdsArr = array();
                $txtDesArr = array();
                foreach($perGeGoodsArr as $k1 => $perGood){
                    // 如果商品没有图片集，把主图作为图片集合
                    count($perGood['imgs'])==0 ? $perGood['imgs'][]=$perGood['itemMainImg'] : 0;

//                    echo '<br><br>---第'. ($key+1) .'个商品中第'. ($k1+1) .'个规格子商品（ID：'. $value['id'] .'）---<br>';
                    $sonGoodNum = count($perGeGoodsArr);
                    // 1. 的到此商品的规格数组
                    $speKVArr = $this->inDbSpe($perGood);
//                    $this->sss($speKVArr, true);
                    $finalGuigeValIdsArr[] = $speKVArr['valueIdArr'];

                    // 2. 得到此商品的主图数组
                    $mainImgIdArr = $this->inDbGoodImg($perGood, $goodID);
//                    $this->sss($mainImgIdArr, true);
                    $goodBannerImgsArr[] = $mainImgIdArr;

                    // 3. 得到此商品的图文描述数组
                    $decImgArr = $this->initGoodDes($perGood);
//                    $this->sss($decImgArr, true);
                    $txtDesArr[] = $decImgArr['desTxt'];

                    // 3.2 处理商品和对应的规格
                    $this->opmGoodsSku($goodID, $perGood['itemMainImg'], $speKVArr['valueIdArr'], $sonGoodNum, $perGood, $decImgArr['desTxt']);
                }
//                echo '<br>'.count($goodBannerImgsArr).' &&&&& '. count($txtDesArr) .'<br>';
                // 4.0 处理商品集合入库，由于本系统限制，只选第一个规格的商品图集，作为主商品的图集
                $this->opmGoodsImg($goodID, $goodBannerImgsArr[0]);
                // 4.1 将商品的规格值入库，单规格无需入库，多规格商品时，每个商品中规格组的id肯定是一致的
                $this->opmGoodsSpec($goodID, $speKVArr['groupIdArr'], $finalGuigeValIdsArr, $sonGoodNum);
                // 5 修改商品文件中的图文富文本内容
                $upArr['content'] = $txtDesArr[0];
                Db::name('goods')->where('goods_id',$goodID)->update($upArr);
            }
        }
    }







    // 0. 商品基本信息先入库，暂时无详情描述，先入zj_goods_image主表获得商品id
    private function goodInDbFunOne($boxInfo){
        $goodID = $this->getDataID('goods', ['net_goodid'=>$boxInfo['id']], 'goods_id');
        $isNew = false;
        if($goodID==-1){
            $isNew = true;  //是全新的数据
            $inArr['goods_name'] = $boxInfo['title'];
            $inArr['net_from'] = $this::net_from;
            $inArr['sellerOpenUid'] = $boxInfo['sellerOpenUid'];
            $inArr['net_brandid'] = isset($boxInfo['brandId']) ? $boxInfo['brandId'] : 0;
            $inArr['net_c1'] = count($boxInfo['goodsCategoryList'])>0 ? $boxInfo['goodsCategoryList'][0]['c1'] : 0;
            $inArr['net_c2'] = count($boxInfo['goodsCategoryList'])>0 ? $boxInfo['goodsCategoryList'][0]['c2'] : 0;
            $inArr['net_c3'] = count($boxInfo['goodsCategoryList'])>0 ? $boxInfo['goodsCategoryList'][0]['c3'] : 0;
            $inArr['net_boximg'] = $boxInfo['mainImg'];
            $inArr['net_goodid'] = $boxInfo['id'];
            $inArr['selling_point'] = "";
            $inArr['category_id'] = count($boxInfo['goodsCategoryList'])>0 ? $boxInfo['goodsCategoryList'][0]['c2'] : 0; // 读取网络的二级分类id
            $inArr['shop_id'] = $this::shop_id;
            $inArr['spec_type'] = count($boxInfo['specificationList'])>1 ? 20 : 10; // 商品是单规格还是多规格
            $inArr['content'] = "";   // 暂时为空，回头修改为第一个子规格商品的详情
            $inArr['sales_initial'] = rand(111,999);
            $inArr['delivery_id'] = 1;  // 配送模板
            $inArr['is_points_gift'] = 0;
            $inArr['is_points_discount'] = 1;
            $inArr['is_enable_grade'] = 0;
            $inArr['is_alone_grade'] = 0;
            $inArr['alone_grade_equity'] = '{"1":"","2":"","3":""}';
            $inArr['is_ind_dealer'] = 0;
            $inArr['wxapp_id'] = $this::wxapp_id;
            $inArr['goods_status'] = $boxInfo['state']==1 ? 10 : 20;
            $inArr['create_time'] = time();
            $inArr['update_time'] = time();
            $goodID = Db::name('goods')->insertGetId($inArr);
        }
        return array('goodID'=>$goodID, 'isNew'=>$isNew);
    }
    // 1. 规格分组和值入库，返回分组和库的相关数据
    private function inDbSpe($perGood){
        $geGroupKVArr = array();
        $geValueKVArr = array();

        $groupIdArr = array();
        $valueIdArr = array();

        $theGE = $perGood['specInfo'];
        $theGEArr = json_decode($theGE, true);

//        $this->sss($theGEArr, true);
//        echo '<br>';

        foreach($theGEArr as $k => $v){
            //$this->sss(trim($k).'***'.trim($v), true);
            $groupName = trim($k);
            $spvalName = trim($v);

            // 查找分组值id，没有则入库
            $groupNameToID = $this->getDataID('spec', ['spec_name'=>$groupName, 'wxapp_id'=>$this::wxapp_id], 'spec_id');
            if($groupNameToID==-1){
                $inArr['spec_name'] = $groupName;
                $inArr['wxapp_id'] = $this::wxapp_id;
                $inArr['create_time'] = time();
                $groupNameToID = Db::name('spec')->insertGetId($inArr);
            }
            $geGroupKVArr[$groupName] = $groupNameToID;
            $groupIdArr[] = $groupNameToID;

            // 查找分组值对应的规格值id，没有则入库
            $spvalNamtToID = $this->getDataID('spec_value', ['spec_value'=>$spvalName, 'spec_id'=>$groupNameToID], 'spec_value_id');
            if($spvalNamtToID==-1){
                $inArr22['spec_value'] = $spvalName;
                $inArr22['spec_id'] = $groupNameToID;
                $inArr22['wxapp_id'] = $this::wxapp_id;
                $inArr22['create_time'] = time();
                $spvalNamtToID = Db::name('spec_value')->insertGetId($inArr22);
            }
            $geValueKVArr[$spvalName] = $spvalNamtToID;
            $valueIdArr[] = $spvalNamtToID;

        }
        return array('geGroupKVArr'=>$geGroupKVArr, 'geValueKVArr'=>$geValueKVArr, 'groupIdArr'=>$groupIdArr, 'valueIdArr'=>$valueIdArr);
    }
    // 2. 入库商品的图片，并返回库中id
    private function inDbGoodImg($perGood, $goodID){
        // 如果规格商品主图和第一张商品图不一致，则组合
//        if($perGood['imgs'][0]!=$perGood['itemMainImg']){
//            $goodImgArr = array_merge([$perGood['itemMainImg']],$perGood['imgs']);
//        }
//        else{
//            $goodImgArr = $perGood['imgs'];
//        }
        $goodImgArr = $perGood['imgs'];
        //echo '<hr><pre>'; print_r($goodImgArr); exit;
        $back = array();
        // echo '<br>';
        foreach($goodImgArr as $k => $img){
            $imgAllPath = trim($img);
            // 此处让图片入库，并返回入库后的id
            //echo '<span> <img src="'.$imgAllPath.'" style="width:100px;height:100px;display:inline-bolck" /> </span>';
            $pathArr = pathinfo($imgAllPath);
            // 图文不重复入库，因为图片file_name字段已做了索引
            $fileID = $this->getImgId($goodID, $imgAllPath, 4);
            $back[] = $fileID;
        }
        return $back;
    }
    // 3. 将商品详情描述图片入库，并返回组装后的图文富文本加密内容
    private function initGoodDes($perGood){
        $desImgArr = $perGood['detailImgs'];
//        $backStr = "";
        $backStr = !empty($perGood['detailTxt']) ? $perGood['detailTxt'] : "";  // mmmodify
        $backArr = array();
        // echo '<br>';
        foreach($desImgArr as $k => $img){
            $imgAllPath = trim($img);
            // 此处让图片入库，并返回入库后的id
            $backStr .= '<p><img src="'.$imgAllPath.'"/></p>';
            //echo '<span> <img src="'.$imgAllPath.'" style="width:100px;height:100px;display:inline-bolck" /> </span>';
        }
        $miStr = htmlspecialchars($backStr, ENT_QUOTES, 'UTF-8');
        return array('desImgIdArr'=>$backArr, 'desTxt'=>$miStr);
    }
    // 4.0 将商品的图片集合入库
    private function opmGoodsImg($goodID, $imgIdArr){
        foreach($imgIdArr as $k => $imgId){
            $id = $this->getDataID('goods_image', ['goods_id'=>$goodID, 'image_id'=>$imgId], 'id');
            if($id == -1){
                $inArr['goods_id'] = $goodID;
                $inArr['image_id'] = $imgId;
                $inArr['wxapp_id'] = $this::wxapp_id;
                $inArr['create_time'] = time();
                Db::name('goods_image')->insertGetId($inArr);
            }
        }
    }
    // 4.1 先将商品的规格值入库，单规格无需入库 对应表zj_goods_spec_rel
    private function opmGoodsSpec($goodID, $guigeGroupIdArr, $finalGuigeValIdsArr, $sonGoodNum){
        /**
        $good1 = array('款式'=>'小号','包装'=>'彩色包装', '颜色'=>'红色');
        $good2 = array('款式'=>'小号','包装'=>'彩色包装', '颜色'=>'黑色');
        $good3 = array('款式'=>'大号','包装'=>'彩色包装', '颜色'=>'红色');
        $good4 = array('款式'=>'大号','包装'=>'彩色包装', '颜色'=>'黑色');
        $groupIdsArr = array(4,3,5);
        $finalValIdsArr = array(0=>array(10,9,16), 1=>array(10,9,17), 2=>array(11,9,16), 3=>array(11,9,17));
         * 入库goods_spec_rel中应该有5条数据，4,10  4,11,  3,9   5,16   5,17
         */
        // 只有多规格商品才入库
        if($sonGoodNum>1){
            // 删除此商品的规格值，重新录入
            $sql44 = "delete from ".getTable('goods_spec_rel')." where goods_id = $goodID";
            $res44 = Db::query($sql44);
            // Array ( [0] => 4 [1] => 3 ) ;
            foreach($guigeGroupIdArr as $cnt11 => $groupId){
                foreach($finalGuigeValIdsArr as $cnt22 => $guigeValIdArr){
                    //Array ( [0] => 7 [1] => 5 ) 和 Array ( [0] => 15 [1] => 5 ) )
                    $valueId = $guigeValIdArr[$cnt11];
                    $spec_relID = $this->getDataID('goods_spec_rel', ['goods_id'=>$goodID, 'spec_id'=>$groupId, 'spec_value_id'=>$valueId], 'id');
                    if($spec_relID==-1){
                        $inArr['goods_id'] = $goodID;
                        $inArr['spec_id'] = $groupId;    // 规格分组id
                        $inArr['spec_value_id'] = $valueId;  // 规格值id
                        $inArr['wxapp_id'] = $this::wxapp_id;
                        $inArr['create_time'] = time();
                        Db::name('goods_spec_rel')->insertGetId($inArr);
                    }
                }
            }
        }
    }
    // 3.2 对应表zj_goods_sku，将商品表和商品sku表中数据一一对应，注意$sonGoodNum字段
    private function opmGoodsSku($goodID, $smallMainImg, $geValIds, $sonGoodNum, $perGood, $perGoodDes)
    {
        $spec_sku_id = "0";
        if($sonGoodNum>1){
            $spec_sku_id = implode('_', $geValIds);
        }
        $theID = $this->getDataID('goods_sku', ['goods_id'=>$goodID, 'spec_sku_id'=>$spec_sku_id], 'goods_sku_id');
        if($theID==-1){
            $inArr['goods_id'] = $goodID;
            $inArr['spec_sku_id'] = $spec_sku_id;    // 规格分组id
            //echo '<hr>'.$goodID.'****'.$smallMainImg; exit;
            $inArr['image_id'] = $this->getImgId($goodID, $smallMainImg, 5);  // 规格值id
            //print_r($perGood);
            $inArr['goods_no'] = $perGood['code'];
            $inArr['net_name'] = $perGood['name'];
            $inArr['net_vip_price'] = $perGood['currVipPrice'];
            $inArr['net_out_price'] = $perGood['freightPrice'];
            $inArr['net_forbidBuyArea'] = isset($perGood['forbidBuyArea']) ? $perGood['forbidBuyArea'] : "";
            $inArr['net_isFreeDelivery'] = $perGood['isFreeDelivery'];
            $inArr['net_minBuyNum'] = $perGood['minBuyNum'];

            //$myPrice = floor($perGood['freightPrice']*1.1); // 我方平台售价，增加百分之十的成本，后面可通过脚本批量修改
            $myPrice = $perGood['freightPrice'] * 1.22;
            //$myPrice = $perGood['freightPrice'];
            $inArr['net_retailPrice'] = isset($perGood['retailPrice']) ? $perGood['retailPrice'] : $myPrice;
            $inArr['net_video'] = $perGood['video'];
            $inArr['net_unit'] = $perGood['unit'];
            $inArr['net_specInfo'] = $perGood['specInfo'];

            $inArr['net_banner_imgs'] = implode('_', $perGood['imgs']);
            $inArr['net_des_txt'] = $perGoodDes;

            $inArr['goods_price'] = $myPrice;    // 我方平台售价，增加百分之十的成本，后面可通过脚本批量修改
            $inArr['line_price'] = $perGood['marketPrice'];
            $inArr['stock_num'] = $perGood['stockNum'];
            $inArr['goods_weight'] = isset($perGood['weight']) ? $perGood['weight'] : 0;
            $inArr['goods_volume'] = isset($perGood['volume']) ? $perGood['volume'] : 0;

            $inArr['wxapp_id'] = $this::wxapp_id;
            $inArr['create_time'] = time();
            $inArr['update_time'] = time();
            Db::name('goods_sku')->insertGetId($inArr);
        }
    }
    // 根据图片url入库并返回入库后的主键id
    private function getImgId($goodID, $imgAllPath, $groupID){
        $pathArr = pathinfo($imgAllPath);
        //print_r($pathArr);
        $fileID = $this->getDataID('upload_file', ['file_name'=>$pathArr['basename']], 'file_id');
        if($fileID==-1){
            $inArr['storage'] = 'local';
            $inArr['group_id'] = $groupID;
            $inArr['back_goodid'] = $goodID;
            $inArr['file_img_allpath'] = $imgAllPath;
            $inArr['file_name'] = $pathArr['basename']; //filename不包含.jpg结尾
            $inArr['file_size'] = 40000;
            $inArr['file_type'] = 'image';
            $inArr['extension'] = $pathArr['extension'];
            $inArr['wxapp_id'] = $this::wxapp_id;
            $inArr['create_time'] = time();
            $fileID = Db::name('upload_file')->insertGetId($inArr);
        }
        return $fileID;
    }
    // 通用性根据名称查找字段，常用于通过name查找id
    private function getDataID($sortName, $where, $backFiled){
        $res = Db::name($sortName)->where($where)->find();
        if($res){
            return $res[$backFiled];
        }
        else{
            return -1;
        }
    }
    private function sss($arr, $isShow=false){
        if($isShow){
            echo '<br>';
            print_r($arr);
        }
    }
}
